package cn.enzo.utils.utils.wx;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

import cn.enzo.utils.utils.Assert;

public class Wxpay implements PayUtils {

	@Override
	public Object UnifiedOrder(Object order) {
		Assert.notNull(order);

		// 校验数据
		verificationOrder(order);

		// 签名
		ValidationSign((UnifiedOrder) order, "DiYethirdLingShi8confidkeys20160");
		return null;
	}

	private void verificationOrder(Object order) {
		if (order instanceof UnifiedOrder) {
			Assert.notNull(((UnifiedOrder) order).getAppid(), "appid is null");
			Assert.notNull(((UnifiedOrder) order).getMch_id(), "mch_id is null");
			Assert.notNull(((UnifiedOrder) order).getNonce_str(), "nonce_str is null");
			Assert.notNull(((UnifiedOrder) order).getBody(), "body is null");
			Assert.notNull(((UnifiedOrder) order).getOut_trade_no(), "out_trade_no is null");
			Assert.notNull(((UnifiedOrder) order).getTotal_fee(), "total_fee is null");
			Assert.notNull(((UnifiedOrder) order).getSpbill_create_ip(), "spbill_create_ip is null");
			Assert.notNull(((UnifiedOrder) order).getTrade_type(), "trade_type is null");
			Assert.notNull(((UnifiedOrder) order).getNotify_url(), "notify_url is null");

		} else {
			throw new IllegalArgumentException();
		}

	}

	//进行签名
	private void ValidationSign(UnifiedOrder order, String key) {
		Assert.notNull(key,"this key is not null");
		Class<? extends UnifiedOrder> class1 = order.getClass();
		Field[] declaredFields = class1.getDeclaredFields();
		List<String> arrayList = new ArrayList<String>();
		try {
			for (Field field : declaredFields) {
				String fieldname = field.getName();
				String methodName = "get" + fieldname.substring(0, 1).toUpperCase() + fieldname.substring(1, fieldname.length());
				Method method2 = class1.getDeclaredMethod(methodName);
				Object invoke = method2.invoke(order);
				if (null != invoke)
					arrayList.add(field.getName() + "=" + invoke);
			}

			Object[] array = arrayList.toArray();
			Arrays.sort(array);
			String join = StringUtils.join(array, "&");
			String stringSignTemp = join + "&key=" + key;
			String upperCase = DigestUtils.md5Hex((stringSignTemp).getBytes("utf-8")).toUpperCase();
			order.setSign(upperCase);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Object doPay(Object object) {
		return null;
	}

}
